package com.leetcode.Offer;

import java.util.Arrays;

public class JZ12 {
    public boolean exist(char[][] board, String word) {
        if (board == null || board[0] == null || board.length == 0 || board[0].length == 0 || word == null || word.equals("")) {
            return false;
        }
        boolean[][] isVisited = new boolean[board.length][board[0].length];

        char[] chars = word.toCharArray();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == chars[0]) {//调用函数
                    if (search(isVisited, board, chars, i, j, 0)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean search(boolean[][] isVisited, char[][] board, char[] chars, int i, int j, int index) {

        if (index == chars.length) {
            return true;
        }
        if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || isVisited[i][j] || board[i][j] != chars[index]) {
            return false;
        }

        isVisited[i][j] = true;
        boolean res = search(isVisited, board, chars, i + 1, j, index + 1)
                || search(isVisited, board, chars, i - 1, j, index + 1)
                || search(isVisited, board, chars, i, j + 1, index + 1)
                || search(isVisited, board, chars, i, j - 1, index + 1);

        if (!res) {
            isVisited[i][j] = false;
        }
        return res;
    }

/*    private boolean search2(boolean[][] isVisited, char[][] board, char[] chars, int i, int j, int index) {
        if (index == chars.length) {
            return true;
        }
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || isVisited[i][j] || board[i][j] != chars[index]) {
            return false;
        }

        isVisited[i][j] = true;

        boolean res = search2(isVisited, board, chars, i + 1, j, index + 1)
                || search2(isVisited, board, chars, i - 1, j, index + 1)
                || search2(isVisited, board, chars, i, j + 1, index + 1)
                || search2(isVisited, board, chars, i, j - 1, index + 1);

        isVisited[i][j] = false;

        return res;
    }*/

}
